package com.hundsun.yr.universal.p2p.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.HsNumberUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog.HSDialogOnItemClickListener;
import com.hundsun.yr.universal.library.widget.HSCircularProgressBar;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.BankAccountBeen;
import com.hundsun.yr.universal.p2p.bean.ManeBean;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;


/**
 * @version V1.0
 * @Title: MineAssetsActivity.java
 * @Description: 我的资产
 * @date 2016-1-13 上午10:08:13
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class MineAssetsActivity extends BaseActivity implements OnClickListener, InitializeView, HSDialogOnItemClickListener {

    /**
     * 总资产进度
     **/
    private HSCircularProgressBar progressBar = null;
    /**
     * 昨日收益
     **/
    private TextView tv_yesterdayincome = null;
    /**
     * 累计收益
     **/
    private TextView tv_totalincome = null;
    /**
     * 总资产
     **/
    private TextView tv_totleassets = null;
    /**可用余额**/
//	private TextView tv_balance=null;
    /**
     * 理财资产
     **/
    private TextView tv_financialassets = null;
    /**
     * 账户余额
     **/
    private TextView tv_accountbalance = null;
    /**冻结金额**/
//	private TextView tv_freeze=null;

    /**
     * 请求接口
     **/
//    private RequestPresenter mPresenter = null;
    /**
     * 绑卡弹窗
     **/
    private HSDialog dialog_bindcard = null;
    /**
     * 实名弹窗
     **/
    private HSDialog dialog_bindname = null;
    /**
     * 账户总资产对象
     **/
    private BankAccountBeen bankAccountBeen;

private HSDialog paypwdDialog = null;
    private   RequestPresenter mPresenter = null;
    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub
        bankAccountBeen = (BankAccountBeen) extras.get(Extras.DATA);
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_mine_assets;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        setSystemBarTintDrawable(getResources().getDrawable(R.color.bg_mine_assets));

        setToolbarTitle(R.string.mine_assets);
        mToolbar.setNavigationIcon(R.drawable.icon_back_light);
        toolbar_title.setTextColor(getResources().getColor(R.color.white));
        mToolbar.setBackgroundColor(getResources().getColor(R.color.bg_mine_assets));
        findView(R.id.line_bottom).setBackgroundColor(getResources().getColor(R.color.bg_mine_assets_line));

        progressBar = findView(R.id.hsCircularProgressBar);
        progressBar.setMarkerDraw(false);
        progressBar.getLayoutParams().width = mScreenWidth * 48 / 75;
        progressBar.getLayoutParams().height = mScreenWidth * 48 / 75;


        tv_yesterdayincome = findView(R.id.tv_yesterdayincome);
        tv_totalincome = findView(R.id.tv_totalincome);
        tv_totleassets = findView(R.id.tv_totleassets);
//		tv_balance=findView(R.id.tv_balance);
        tv_financialassets = findView(R.id.tv_financialassets);
        tv_accountbalance = findView(R.id.tv_accountbalance);
//		tv_freeze=findView(R.id.tv_freeze);

        refreshUI(bankAccountBeen);
        loadingData();
        mPresenter = new InitializePresenterImpl(mContext, this);
    }

    /**
     * 请求数据
     */
    private void loadingData() {
       /* mPresenter = new InitializePresenterImpl(this, this);
        mPresenter.loadingData(TaskConstants.TASK_ASSET, getString(R.string.root_url), Constants.EVENT_REFRESH_DATA,
                ApiConstants.accountAsset(mContext), false);*/

    }

    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_rechange://充值

                if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_BINDCARD), "YES")) {
                    if (TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES")) {

                        dialog_bindcard = new HSDialog(getString(R.string.tips), getString(R.string.tips_rechange_bindcard),
                                getString(R.string.cancel), getString(R.string.tips_go_bindcard), this,
                                this).setCancelable(false);//.setOnDismissListener(this);
                        dialog_bindcard.show();

                    } else {
                        dialog_bindname = new HSDialog(getString(R.string.tips), getString(R.string.open_account),
                                getString(R.string.cancel), getString(R.string.tips_go_set), this,
                                this).setCancelable(false);//.setOnDismissListener(this);
                        dialog_bindname.show();
                    }
                } else {
                    readyGo(RechangeNewActivity.class);
                }

                break;
            case R.id.btn_withdraw://提现

                if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_BINDCARD), "YES")) {
                    if (TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_ACCOUNT), "YES")) {
                        dialog_bindcard = new HSDialog(getString(R.string.tips), getString(R.string.tips_withdraw_bindcard),
                                getString(R.string.cancel), getString(R.string.tips_go_bindcard), this,
                                this).setCancelable(false);//.setOnDismissListener(this);
                        dialog_bindcard.show();
                    } else {
                        dialog_bindname = new HSDialog(getString(R.string.tips), getString(R.string.open_account),
                                getString(R.string.cancel), getString(R.string.tips_go_set), this,
                                this).setCancelable(false);//.setOnDismissListener(this);
                        dialog_bindname.show();
                    }
                } else {
                    readyGo(WithDrawActivity.class);
                }

                break;

            default:
                break;
        }
    }


    @Override
    public <T> void initializeViews(String task_name, T data) {
        /*// TODO Auto-generated method stub
        if (TextUtils.equals(task_name, TaskConstants.TASK_ASSET)) {

        }*/
        switch (task_name){
            case TaskConstants.TASK_CARDBIND:
                Gson gson =new Gson();
                ManeBean maneBean = gson.fromJson(String.valueOf(data), ManeBean.class);
                String zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        "bindcardpagerst", sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap1 = new HeaderMap();
                headerMap1.setMap(hearder1);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, maneBean.getHtml());
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
                readyGo(WebOpenAccountActivity.class, bundle);
                break;
            case TaskConstants.TASK_SETBANKPWD:
                if (data == null) {
                    return;
                }

                UpdatePayPwdBeen mUpdatePayPwdBeen = (UpdatePayPwdBeen) data;

                //现在做另外一种操作
                String postData = null;
                try {
                    postData = "accountId=" + URLEncoder.encode(mUpdatePayPwdBeen.data.accountId.toString(), "utf-8") + "&acqRes=" + URLEncoder.encode(mUpdatePayPwdBeen.data.acqRes.toString(), "utf-8") +
                            "&bankCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.bankCode.toString(), "utf-8") + "&channel=" + URLEncoder.encode(mUpdatePayPwdBeen.data.channel.toString(), "utf-8") +
                            "&idNo=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idNo.toString(), "utf-8") + "&idType=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idType.toString(), "utf-8") + "&instCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.instCode.toString(), "utf-8") + "&lastSrvAuthCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.lastSrvAuthCode == null ? "" : mUpdatePayPwdBeen.data.lastSrvAuthCode.toString(), "utf-8") +
                            "&mobile=" + URLEncoder.encode(mUpdatePayPwdBeen.data.mobile.toString(), "utf-8") + "&name=" + URLEncoder.encode(mUpdatePayPwdBeen.data.name.toString(), "utf-8") + "&notifyUrl=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.notifyUrl.toString(), "utf-8") + "&retUrl=" + URLEncoder.encode(mUpdatePayPwdBeen.data.retUrl.toString(), "utf-8") + "&seqNo=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.seqNo.toString(), "utf-8") + "&sign=" + URLEncoder.encode(mUpdatePayPwdBeen.data.sign.toString(), "utf-8") + "&smsCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.smsCode == null ? "" : mUpdatePayPwdBeen.data.smsCode.toString(), "utf-8") + "&txCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txCode.toString(), "utf-8") +
                            "&txDate=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txDate.toString(), "utf-8") + "&txTime=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txTime.toString(), "utf-8") + "&version=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.version.toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                Bundle bundle1 = new Bundle();
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.set_paywd));
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_URL, mUpdatePayPwdBeen.url);
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_PARAMS, postData);
                bundle1.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.POSTDATA.getIntValue());
                bundle1.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebSetPasswordActivity.class, bundle1);
                break;
        }
    }

    /**
     * 刷新UI
     */
    private void refreshUI(BankAccountBeen account) {
        if (account == null) return;
        //昨日收益
        tv_yesterdayincome.setText(getString(R.string._rmb, HsNumberUtils.moneyThousandsFormat("0")));
        //累计收益
        tv_totalincome.setText(getString(R.string._rmb, HsNumberUtils.moneyThousandsFormat("0")));
        //总资产
        tv_totleassets.setText(HsNumberUtils.moneyTenThousandsFormat(account.currBal));
        //理财资产
        tv_financialassets.setText(getString(R.string._rmb, HsNumberUtils.moneyThousandsFormat(account.getFinancialAssets().toString())));
        //账户余额
        tv_accountbalance.setText(getString(R.string._rmb, HsNumberUtils.moneyThousandsFormat(account.availBal)));
        //progressbar
        progressBar.setProgress(account.displayProgress());
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onItemClick(Object o, int position) {
        // TODO Auto-generated method stub
        if ((HSDialog) o == dialog_bindcard) {
            if (position != -1) {
                if (TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_PAYPWD), "YES")){
                    bindCar();
                }else {
                    paypwdDialog = new HSDialog(getString(R.string.tips), getString(R.string.tips_nopaypwd),
                            getString(R.string.cancel), getString(R.string.tips_go_set), mContext, this).setCancelable(false);
                    paypwdDialog.show();
                }
            }
        } else if ((HSDialog) o == dialog_bindname) {
            if (position != -1) {
                readyGo(OpenAccountBankActivity.class);
            }
        } else if ((HSDialog) o == paypwdDialog) {
            if (position != -1) {
//               String  zwgt_data = BaseRequestTool2.getFormatedDateString();
//                JSONObject map1 = new JSONObject();
//
//                try {
//                    map1.put("vcode", "");
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//                JSONObject jsonParams = CommTool.getJSONParams(map1, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
//                mPresenter.loadingData(TaskConstants.TASK_SETBANKPWD, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, Constants.EVENT_DATA,
//                        jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, sharedPreferences
//                                .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                readyGo(ManagementActivity.class);
            }
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (dialog_bindcard != null && dialog_bindcard.isShowing()) {
                dialog_bindcard.dismiss();
                return true;
            } else if (dialog_bindname != null && dialog_bindname.isShowing()) {
                dialog_bindname.dismiss();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }
    private void bindCar(){
        //绑定银行卡
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        mPresenter.loadingData(TaskConstants.TASK_CARDBIND, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_CARDBIND,
                Constants.EVENT_DATA,jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_user_test) + TaskConstants.TASK_CARDBIND,
                        sharedPreferences.getShareProf(UserInfo.USER_NO),
                        sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }
}
